// 实现modal弹出框的拖拽
export default {
  inserted (el, binding) {
    const header = el.querySelector('.ant-modal-header')
    const modal = el.querySelector('.ant-modal')

    if (!header || !modal) return

    let isDragging = false
    let startX = 0
    let startY = 0
    let left = 0
    let top = 0

    // 创建一个ResizeObserver实例并定义回调函数
    const resizeObserver = new ResizeObserver(entries => {
      for (const entry of entries) {
          // 每次宽度变化时，entry.contentRect.width会给出新的宽度值
          const { width, height } = entry.contentRect
          if (width) {
            // 初始居中
            left = (window.innerWidth - width) / 2
            top = (window.innerHeight - height) / 2
            updatePosition()
          }
      }
    })

    // 观察目标元素
    resizeObserver.observe(modal)

    header.style.cursor = 'move'

    header.addEventListener('mousedown', onMouseDown)

    function onMouseDown (e) {
      isDragging = true
      startX = e.clientX
      startY = e.clientY

      document.addEventListener('mousemove', onMouseMove)
      document.addEventListener('mouseup', onMouseUp)
    }

    function onMouseMove (e) {
      if (!isDragging) return

      const dx = e.clientX - startX
      const dy = e.clientY - startY

      left += dx
      top += dy

      // 边界检测
      const { width, height } = modal.getBoundingClientRect()
      left = Math.max(0, Math.min(left, window.innerWidth - width))
      top = Math.max(0, Math.min(top, window.innerHeight - height))

      startX = e.clientX
      startY = e.clientY
      updatePosition()
    }

    function onMouseUp () {
      isDragging = false
      document.removeEventListener('mousemove', onMouseMove)
      document.removeEventListener('mouseup', onMouseUp)
    }

    function updatePosition () {
      modal.style.top = top + 'px'
      modal.style.left = left + 'px'
    }

    // 窗口大小变化时重新居中
    window.addEventListener('resize', () => {
      const { width, height } = modal.getBoundingClientRect()
      left = (window.innerWidth - width) / 2
      top = (window.innerHeight - height) / 2
      updatePosition()
    })
  },

  bind (el, binding) {
  },

  unbind (el, binding) {
  }
}
